package com.zzuli.practice.controller;


import com.zzuli.practice.entity.Result;
import com.zzuli.practice.service.impl.CommentService;
import com.zzuli.practice.service.impl.HeaderImgService;
import com.zzuli.practice.service.impl.LoginService;
import com.zzuli.practice.service.impl.PostService;
import com.zzuli.practice.util.Constant;
import com.zzuli.practice.util.PracticeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@CrossOrigin
@EnableTransactionManagement // 开启事务
@RequestMapping("/header")
public class HeaderImgController implements Constant {

    private static final Logger logger = LoggerFactory.getLogger(HeaderImgController.class);

    @Autowired
    private HeaderImgService headerImgService;

    @Value("${practice.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${practice.path.upload}")
    private String uploadPath;

    @Autowired
    private LoginService loginService;

    @Autowired
    private PostService postService;

    @Autowired
    private CommentService commentService;


    // 设置事务传播行为
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result upLoad(String username,  MultipartFile headimage){

        Result result = new Result();

        System.out.println(username);
        System.out.println(headimage);

        if (headimage == null){
            result.setStatusCode(FAILURE);
            result.setMessage("文件为空!");
            return result;
        }

        String fileName = headimage.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)){
            result.setStatusCode(FAILURE);
            result.setMessage("文件格式错误!");
            return result;
        }

        // 生成随机文件名
        fileName = PracticeUtil.generateUUID() + suffix;
        // 确定文件存放路径
        File dest = new File(uploadPath + "/" + fileName);
        try {
            // 存储文件
            headimage.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败，服务器发生异常！" ,e);
        }
        String headerUrl = domain + contextPath + "/header/headerimg/" + fileName;
        int i = headerImgService.updateHeaderImg(username, headerUrl);
        postService.updateHeaderImg(username, headerUrl);
        commentService.updateHeaderImg(username, headerUrl);
        if (i == 1){
            result.setStatusCode(SUCCESS);
            result.setMessage("上传成功!");
            return result;
        }

        result.setStatusCode(FAILURE);
        result.setMessage("上传失败!");
        return result;
    }

    @RequestMapping("/getheader/{username}")
    public String getHeader(@PathVariable("username") String username){
        return loginService.selectByUserName(username).getHeaderimg();
    }

    @RequestMapping("/headerimg/{fileName}")
    public void getHeaderImg(@PathVariable("fileName") String fileName, HttpServletResponse response){
        // 服务器存放的路径
        fileName = uploadPath + "/" + fileName;
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(fileName);
        ) {

            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1){
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("头像获取失败：" + e.getMessage());
        }
    }

}
